import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/product_template_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

final textStyle = TextStyle(
    color: Color.fromRGBO(11, 123, 118, 1.0),
    decoration: TextDecoration.none,
    fontSize: 18.sp);

class BulletinBoard extends StatefulWidget {
  BulletinBoard({
    Key? key,
  }) : super(key: key);

  @override
  _BulletinBoardState createState() => _BulletinBoardState();
}

class _BulletinBoardState extends State<BulletinBoard> {
  // List<Employee> _employees = getEmployeeData();
  late DataSource _dataSource;
  final DataGridController _controller = DataGridController();
  late ScrollController _verticalScrollController = ScrollController();
  late Timer timer;
  double _currentRow = 0;
  late List<StockQuant> ylkData;
  late Timer _timer;
  late DateTime dateTime;
  @override
  void initState() {
    super.initState();
    ylkData = [];
    timer = Timer.periodic(Duration(seconds: 3), (Timer t) => autoScroll());
    _loadData();
    _dataSource = DataSource(ylkData);
    dateTime = new DateTime.now();
    this._timer = new Timer.periodic(Duration(seconds: 1), setTime);
  }

  void setTime(Timer timer) {
    setState(() {
      dateTime = new DateTime.now();
    });
  }

  @override
  Widget build(BuildContext context) {
    // var size = MediaQuery.of(context).size;
    // var width = size.width;
    // var height = size.height;
    return Card(
        // margin:  const EdgeInsets.all(24.0),
        clipBehavior: Clip.antiAlias,
        elevation: 1.0,
        // color: Colors.red,
        child: _buildDataGrid());
  }

  @override
  void dispose() {
    timer.cancel();
    _timer.cancel();
    super.dispose();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await ProductTemplateOdooApi.bulletinBoard();
    if (responseBodyApi.success!) {
      _dataSource = DataSource(responseBodyApi.data);
      setState(() {});
    }
  }

  Future<List<StockQuant>> getData(String comment, int limit) async {
    List<StockQuant> result = [];
    ResponseBodyApi res =
        await StockQuantOdooApi.getDataByComment(comment, limit);
    if (res.success!) {
      res.data.forEach((e) {
        Map<String, dynamic> map = e;
        result.add(StockQuant.fromMap2(map));
      });
    }
    return result;
  }

  autoScroll() {
    if (_verticalScrollController.position.pixels ==
        _verticalScrollController.position.maxScrollExtent) {
      _currentRow = 0;
    } else {
      _currentRow += 5;
    }
    _controller.scrollToCell(_currentRow, 1, canAnimate: true);
  }

  _buildDataGrid() {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/bg/bg1.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        children: [
          Container(
            // width: width,
            alignment: Alignment.center,
            child: Padding(
              padding: EdgeInsets.all(10),
              child: Text(
                //${dateTime.year}年${dateTime.month}月${dateTime.day}日     ${dateTime.hour}时${dateTime.minute.toString().padLeft(2, '0')}分${dateTime.second.toString().padLeft(2, '0')}秒
                "订单生产进度跟踪看板",
                style: TextStyle(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    decoration: TextDecoration.none,
                    fontSize: 25.sp),
              ),
            ),
          ),
          Expanded(
            // width: width,
            // height: 200.h,
            child: SfDataGridTheme(
                data: SfDataGridThemeData(
                  gridLineColor: Color.fromRGBO(46, 47, 83, 1.0),
                  headerColor: Colors.transparent,
                  headerHoverColor: Colors.transparent,
                ),
                child: SfDataGrid(
                  controller: _controller,
                  verticalScrollController: _verticalScrollController,
                  columnWidthMode: ColumnWidthMode.fill,
                  source: _dataSource,
                  rowHeight: 55.h,
                  headerRowHeight: 55.h,
                  gridLinesVisibility: GridLinesVisibility.both,
                  headerGridLinesVisibility: GridLinesVisibility.both,
                  columns: [
                    GridColumn(
                        columnName: '序号',
                        maximumWidth: 90.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '序号',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '客户名称',
                        //  maximumWidth: 100.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '客户名称',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '销售单号',
                        maximumWidth: 130.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '销售单号',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '业务员',
                        maximumWidth: 130.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '业务员',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '产品名称',
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '产品名称',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '规格型号',
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '规格型号',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '交货日期',
                        maximumWidth: 130.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '交货日期',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '订单数量',
                        maximumWidth: 123.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '订单数量',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '生产数量',
                        maximumWidth: 123.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '生产数量',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '已入库数量',
                        maximumWidth: 123.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '已入库数',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '生产进度',
                        maximumWidth: 140.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '生产进度',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '已发货数',
                        maximumWidth: 123.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '已发货数',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '发货进度',
                        maximumWidth: 140.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '发货进度',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                    GridColumn(
                        columnName: '未发货数',
                        maximumWidth: 123.r,
                        label: Container(
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.center,
                            child: Text(
                              '未发货数',
                              style: textStyle,
                              overflow: TextOverflow.ellipsis,
                            ))),
                  ],
                )),
          ),
        ],
      ),
    );
  }
}

Widget buildSoftwareProficiency(dynamic value) {
  Widget getLinearProgressBar(num progressValue) {
    return Container(
      width: 120.r,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            height: 22.r,
            width: 80.r,
            child: ClipRRect(
                // 边界半径（`borderRadius`）属性，圆角的边界半径。
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
                child: LinearProgressIndicator(
                  value: progressValue / 100,
                  valueColor: AlwaysStoppedAnimation<Color>(progressValue < 50
                      ? Colors.red
                      : progressValue < 70
                          ? Colors.yellow
                          : Colors.green),
                  backgroundColor:
                      progressValue < 50 ? Colors.red[100] : Colors.green[100],
                )),
          ),
          Text(
            ' ' + (progressValue.toString() + '%'),
            style: TextStyle(
                color: Colors.red, //Color.fromRGBO(255, 255, 255, 1),
                decoration: TextDecoration.none,
                fontSize: 20.sp),
          ),
        ],
      ),
    );
  }

  return getLinearProgressBar(value * 100);
}

class DataSource extends DataGridSource {
  DataSource(List<dynamic> stockQuantList) {
    // 客户名称、销售单号、业务员、产品名称、规格型号、交货日期、订单数量、生产数量、已入库数量（成品入库数量）、生产进度（生产数量/订单数量）、已发货数(成品发货出库数量)、发货进度（已发货数量/订单数量）、未发货数（订单数量-已发货数量）
    int index = 1;
    dataGridRows = stockQuantList
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<num>(columnName: '序号', value: index++),
              DataGridCell<String>(columnName: '客户名称', value: dataGridRow['partner'] != false
                  ? dataGridRow['partner']['name']
                  : ''),
              DataGridCell<String>(columnName: '销售单号', value: dataGridRow['sale_order'] != false
                  ? dataGridRow['sale_order']['name']
                  : ''),
              DataGridCell<String>(columnName: '业务员', value: dataGridRow['user'] != false
                  ? dataGridRow['user']['name']
                  : ''),
              DataGridCell<String>(columnName: '产品名称', value: dataGridRow['product_name'] != false
                  ? dataGridRow['product_name']
                  : ''),
              DataGridCell<String>(columnName: '规格型号', value: dataGridRow['description'] != false
                  ? dataGridRow['description']
                  : ''),
              DataGridCell<String>(columnName: '交货日期', value: dataGridRow['date_deadline'] != false
                  ? dataGridRow['date_deadline']
                  : ''),
              DataGridCell<num>(columnName: '订单数量', value: dataGridRow['product_uom_qty'] != false
                  ? dataGridRow['product_uom_qty']
                  : ''),
              DataGridCell<num>(columnName: '生产数量', value: dataGridRow['qty_produced'] != false
                  ? dataGridRow['qty_produced']
                  : ''),
              DataGridCell<num>(columnName: '已入库数量', value: dataGridRow['Inventory_quantity'] != false
                  ? dataGridRow['Inventory_quantity']
                  : ''),
              DataGridCell<num>(columnName: '生产进度', value: dataGridRow['production_schedule'] != false
                  ? dataGridRow['production_schedule']
                  : ''),
              DataGridCell<num>(columnName: '已发货数', value: dataGridRow['qty_done'] != false
                  ? dataGridRow['qty_done']
                  : ''),
              DataGridCell<num>(columnName: '发货进度', value: dataGridRow['delivery_schedule'] != false
                  ? dataGridRow['delivery_schedule']
                  : ''),
              DataGridCell<num>(columnName: '未发货数', value: dataGridRow['undelivered_quantity'] != false
                  ? dataGridRow['undelivered_quantity']
                  : ''),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        color: Colors.transparent,
        cells: row.getCells().map<Widget>((dataGridCell) {
          return dataGridCell.columnName == '生产进度' ||
                  dataGridCell.columnName == '发货进度'
              ? buildSoftwareProficiency(dataGridCell.value)
              : Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    dataGridCell.value.toString(),
                    style: TextStyle(
                        fontSize: 20.sp,
                        color: Colors.white,
                        decoration: TextDecoration.none),
                    overflow: TextOverflow.ellipsis,
                  ));
        }).toList());
  }
}
